Idea of templates

Please go through the codes one by one.
Youtube link for further learning

  1. Let us say we have created a code to calculate square of an input number:
    	#include<iostream>
    	int square(int a)
    	{
    	return a*a;
    	}
    	int main()
    	{
    	std::cout<<square(5)<<std::endl;
    	std::cout<<square(5.5)<<std::endl;
    	std::cout<<square(5.5f)<<std::endl;
    	}
    	/*
    	It will generate the output as :
    	25
    	25 
    	25
    	*/
    
  2. 	#include<iostream>
    	int square(int a)
    	{
    	return a*a;
    		}
    	int square(double a)
    	{
    	return a*a;
    		}
    	int square(float a)
    	{
    	return a*a;
    	}
    	int main()
    	{
    	std::cout<<square(5)<<std::endl;
    	std::cout<<square(5.5)<<std::endl;
    	std::cout<<square(5.5f)<<std::endl;
    	}
    	/*
    	It will generate the output as :
    	25
    	30 
    	30
    	*/
    
  3. 	#include<iostream>
    	int square(int a)
    	{
    	return a*a;
    		}
    	double square(double a)
    	{
    	return a*a;
    		}
    	float square(float a)
    	{
    	return a*a;
    	}
    	int main()
    	{
    	std::cout<<square(5)<<std::endl;
    	std::cout<<square(5.5)<<std::endl;
    	std::cout<<square(5.5f)<<std::endl;
    	}
    	/*
    	It will generate the output as :
    	25
    	30.25 
    	30.25
    	*/
    

So you see, we can make mistakes if we are dealing with long codes, to avid such mistakes, instead we use idea of templates in c++.

Use of Templates

	#include<iostream>
	template <typename T>
	T square(T a)
	{
	return a*a;
	}
	int main()
	{
	std::cout<<square(5)<<std::endl;
	std::cout<<square(5.5)<<std::endl;
	std::cout<<square(5.5f)<<std::endl;
	}
	/*
	It will generate the output as :
	25
	30.25 
	30.25
	*/

OR

	#include<iostream>
	template <typename T>
	T square(T a)
	{
	return a*a;
	}
	int main()
	{
	std::cout<<square<int>(5)<<std::endl;
	std::cout<<square<double>(5.5)<<std::endl;
	std::cout<<square<float>(5.5f)<<std::endl;
	}
	/*
	It will generate the output as :
	25
	30.25 
	30.25
	*/